<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible= true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色对话框" :visible.sync="addDialogVisible" width="50%">
        <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="70px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc" style="width: 300px;"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 角色列表区 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand" label="">
          <template slot-scope="scope">
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag> {{item1.authName}}<i class="el-icon-caret-right"></i></el-tag>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success"> {{item2.authName}}<i class="el-icon-caret-right"></i> </el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,i3) in item2.children"
                      :key="item3.id">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre> {{scope.row}} </pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"
                @click="showSetRightDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="30%" @close="setRightDialogClosed">
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all ref="treeRef"
        :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
  export default {
    data() {
      return {
        rolesList: [],
        addDialogVisible: false,
        addRoleForm: {
          roleName: '',
          roleDesc: ''
        },
        setRightDialogVisible: false,
        rightsList: [],
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        defKeys: [],
        roleId:'',
        addRoleFormRules: {
          roleName: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }],
        }
      }
    },

    created() {
      this.getRolesList()
    },

    methods: {
      async getRolesList() {
        const {
          data: res
        } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error('获取角色失败')
        }
        this.rolesList = res.data
        console.log(this.rolesList)
      },
      async addRole() {
        this.$refs.addRoleFormRef.validate(valid => {
          if (!valid) return
        })
        const {
          data: res
        } = await this.$http.post('roles', this.addRoleForm)
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('创建角色失败')
        }
        this.$message.success('创建用户成功')
        this.addDialogVisible = false
        this.getRolesList()
      },
      async deleteRole(id) {
        const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        const {
          data: res
        } = await this.$http.delete('roles/' + id)
        console.log(confirmResult);
        this.getRolesList()

      },
      async showSetRightDialog(role) {
        this.roleId = role.id
        const {
          data: res
        } = await this.$http.get('rights/tree')
        if (res.meta.status !== 200) return this.$message.error('获取权限数据失败！')
        this.rightsList = res.data
        // console.log(this.rightsList);
        this.getLeafKeys(role, this.defKeys)
        this.setRightDialogVisible = true
      },
      // 通过递归的形式，获取所有三级权限的id,并保存到defKeys
      getLeafKeys(node, arr) {
        if (!node.children) {
          return arr.push(node.id)
        }
        node.children.forEach(item => this.getLeafKeys(item, arr))
      },
      setRightDialogClosed() {
        this.defKeys = []
      },
     async allotRights(){
        const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
        const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
        if(res.meta.status !==200){ this.$message.error('分配权限失败!')}
        this.$message.success('分配权限成功!')
        this.getRolesList()
        this.setRightDialogVisible = false
      }
    },

  }
</script>

<style lang="less">
  .el-col {
    text-align: left;
  }

  .el-tag {
    margin-top: 10px;
    margin-right: 10px;
  }
</style>
